<template>
<label :class="{'is-invalid-label': hasError}">{{ label }}
  <field-error v-show="hasError" :err="errMsg" />
  <ul :class="['et-list', {'is-invalid-input': hasError}]" :style="styles">
    <li v-for="(item, idx) in listItems" :key="idx">
      <div class="grid-x">

        <div class="cell small-10">

          <a v-if="itemHandler" @click="() => { itemHandler(item); }">{{ item.txt }}</a>
          <span v-if="!itemHandler">{{ item.txt }}</span>

        </div>

        <div class="cell small-2 text-center">
          <slot :item="item"></slot>
        </div>

      </div>
    </li>
  </ul>
</label>
</template>

<script>
import FieldError from './FieldError';

export default {

  components: {
    FieldError
  },

  props: {
    items: {
      type: Array,
      default() {
        return [];
      }
    },
    name: {
      type: String,
      required: true
    },
    label: {
      type: String,
      required: true
    },
    itemHandler: {
      type: Function
    },
    isRequired: {
      type: Boolean
    },
    errMsg: {
      type: String
    },
    styles: {
      type: Object
    }
  },

  data() {
    return {
      listItems: [],
      isInit: true
    };
  },

  computed: {
    hasError() {
      return this.isRequired && this.listItems.length === 0 && !(this.isInit);
    }
  },

  watch: {
    listItems() {
      this.$emit('listItems', {
        key: this.name,
        val: this.listItems.length === 0 ? [] : this.listItems
      });
    },
    items() {
      if (this.items) {
        this.listItems = this.items;
        this.isInit = false;
      }
    }
  },

  methods: {
    reset() {
      this.listItems = [];
      this.isInit = true;
    },

    removeItem(item) {
      this.listItems = this.listItems.filter((i) => {
        return i.id !== item.id;
      });
    },

    addItem(item) {
      this.isInit = false;
      let exist = this.listItems.some( (i) => item.id === i.id );
      if (!exist) {
        this.listItems.push(item);
      }
    }
  },

  mounted() {
    if (this.items && this.items.length > 0 && this.listItems.length === 0) {
      this.listItems = this.items;
      this.isInit = false;
    }
  }
};
</script>
